package com.yb0os1.SimpleJDKProxy;

import com.yb0os1.SimpleJDKProxy.MyInterface;
import com.yb0os1.SimpleJDKProxy.ProxyFactory;

import java.lang.reflect.Field;

public class SimpleJDKProxyTest {
    public static void main(String[] args) throws Exception {
        MyInterface proxy = ProxyFactory.createProxy(new LogHandler(new MyInterface() {
            @Override
            public void fun1() {
                System.out.println(1);
            }

            @Override
            public void fun2() {
                System.out.println(2);

            }

            @Override
            public void fun3() {
                System.out.println(3);

            }
        }));
        proxy.fun1();
        proxy.fun2();
        proxy.fun3();
    }

    static class LogHandler implements com.yb0os1.SimpleJDKProxy.MyHandler {
        MyInterface myInterface;

        public LogHandler(MyInterface myInterface) {
            this.myInterface = myInterface;
        }

        @Override
        public void setProxy(MyInterface proxy) {//传入的是代理对象
            Class<? extends MyInterface> aClass = proxy.getClass();
            Field field = null;
            try {
                field = aClass.getDeclaredField("myInterface");
                field.setAccessible(true);
                field.set(proxy, myInterface);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        @Override
        public String functionBody(String methodName) {
            StringBuilder sb = new StringBuilder();
            sb.append("System.out.println(\"before\");")
                    .append("myInterface." + methodName + "();")
                    .append("System.out.println(\"after\");");
            return sb.toString();
        }
    }
}